package transformation;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.emf.ecore.EObject;
import org.eclipse.uml2.uml.FinalState;
import org.eclipse.uml2.uml.Pseudostate;
import org.eclipse.uml2.uml.State;
import org.eclipse.uml2.uml.Transition;

import CDPackage.CDPackageFactory;
import CDPackage.ClassDiagram;
import CDPackage.Clazz;
import CDPackage.Ref;
import names.Names;
/***
 * 
 * @author Bo Cai
 *
 */
public class Transformation {
	protected static final CDPackageFactory factory = CDPackageFactory.eINSTANCE;

	public static ClassDiagram uml2ClassDiagram(List<EObject> uml) {
		if (uml == null)
			return null;

		// initialisation des class server et state
		ClassDiagram cd = factory.createClassDiagram();
		Clazz server = factory.createClazz();
		Clazz state = factory.createClazz();

		server.setName(Names.serverClassName);
		Ref stateRef = factory.createRef();
		stateRef.setName(Names.stateFieldName);
		stateRef.setUpper(1);
		stateRef.setLower(1);
		stateRef.setType(state);
		server.getReferences().add(stateRef);
		cd.getClazzes().add(server);

		state.setName(Names.stateClassName);
		Ref serverRef = factory.createRef();
		serverRef.setName(Names.serverFieldName);
		serverRef.setUpper(1);
		serverRef.setLower(1);
		serverRef.setType(server);
		state.getReferences().add(serverRef);
		cd.getClazzes().add(state);

		Clazz temp = null;
		CDPackage.Operation op = null;
		ArrayList<CDPackage.Operation> ops = new ArrayList<CDPackage.Operation>();

		for (EObject o : uml) {
			if (o instanceof State) {
				temp = factory.createClazz();
				temp.setName(((State) o).getName());
				temp.setSuper(state);
				cd.getClazzes().add(temp);
			} else if (o instanceof Transition) {

				op = factory.createOperation();
				op.setName(((Transition) o).getName());

				ops.add(op);

			} else if (o instanceof Pseudostate) {
				Clazz init = factory.createClazz();
				init.setName(((Pseudostate) o).getName());
				init.setSuper(state);
				cd.getClazzes().add(init);
			} else if (o instanceof FinalState) {
				Clazz end = factory.createClazz();
				end.setName(((FinalState) o).getName());
				end.setSuper(state);
				cd.getClazzes().add(end);
			}
		}

		// ajout des operations dans chaque class
		for (Clazz c : cd.getClazzes())
			c.getOperations().addAll(ops);

		return cd;

	}
}
